package com.csea.tools.vo;

import com.csea.tools.enums.ResultEnum;
import lombok.Data;
import org.springframework.validation.BindingResult;

import java.util.Objects;

/**
 * @author Csea
 * @title
 * @date 2019/12/26 14:28
 */
@Data
public class JsonResultVo<T> {
    private Integer code;

    private String message;

    private T data;


    public static <T> JsonResultVo<T> success(String msg) {
        return new JsonResultVo<>(ResultEnum.SUCCESS.getCode(), msg, null);
    }

    public static <T> JsonResultVo<T> success(T data) {
        return new JsonResultVo<>(ResultEnum.SUCCESS.getCode(), data);
    }

    public static <T> JsonResultVo<T> success() {
        return new JsonResultVo<>(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage());
    }

    public static <T> JsonResultVo<T> failure(ResultEnum resultEnum) {
        return new JsonResultVo<>(resultEnum.getCode(), resultEnum.getMessage());
    }

    public static <T> JsonResultVo<T> failure(ResultEnum resultEnum, String message) {
        return new JsonResultVo<>(resultEnum.getCode(), message);
    }

    public static <T> JsonResultVo<T> failure(ResultEnum resultEnum, BindingResult bindingResult) {
        return new JsonResultVo<>(resultEnum.getCode(),
                Objects.requireNonNull(bindingResult.getFieldError()).getField() + " " + bindingResult.getFieldError().getDefaultMessage());
    }


    private JsonResultVo(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    private JsonResultVo(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    public JsonResultVo(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}
